package com.community.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.community.common.config.BizException;
import com.community.common.mapper.*;
import com.community.common.pojo.domain.*;
import com.community.common.pojo.dto.sync.SyncDataBaseDto;
import com.community.common.pojo.dto.sync.SyncDataFriendDto;
import com.community.common.pojo.dto.sync.SyncDataPeopleDto;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.sync.SyncDataBaseVO;
import com.community.common.pojo.vo.sync.SyncDataFriendVo;
import com.community.common.pojo.vo.sync.SyncDataPeopleVo;
import com.community.common.util.ImgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhu
 * @Desc: 数据同步
 */
@RestController
@RequestMapping("/syncdata")
@Slf4j
public class SyncController {

    private static final String SYNC_PWD = "kht1234qwer";

    @Resource
    CommunityMapper communityMapper;

    @Resource
    BuildingMapper buildingMapper;

    @Resource
    HouseMapper houseMapper;

    @Resource
    PublicUserMapper publicUserMapper;

    @Resource
    OwnerFriendMapper ownerFriendMapper;

    @Resource
    OwnerHouseMapper ownerHouseMapper;

    @Resource
    PictureMapper pictureMapper;

    @Resource
    FriendHouseMapper friendHouseMapper;

    @Resource
    UserPermissionMapper userPermissionMapper;


    @PostMapping("/base")
    public MyResponse base(@RequestBody SyncDataBaseDto dto) {
        try {
            if (ObjectUtils.isEmpty(dto) || StringUtils.isAnyBlank(dto.getXqId(), dto.getPwd())) {
                return MyResponse.fail("入参不能为空");
            }
            if (!SYNC_PWD.equals(dto.getPwd())) {
                return MyResponse.fail("错啦错啦");
            }
            Community community = communityMapper.selectById(dto.getXqId());
            List<Building> buildings = buildingMapper.selectList(new LambdaQueryWrapper<Building>().eq(Building::getXqId, dto.getXqId()));
            if (ObjectUtils.isEmpty(community) || CollectionUtils.isEmpty(buildings)) {
                return MyResponse.fail("无基础数据");
            }

            List<House> houses = new ArrayList<>();
            buildings.forEach(e -> {
                houses.addAll(houseMapper.selectList(new LambdaQueryWrapper<House>().eq(House::getLdId, e.getId())));
            });

            List<UserPermission> userPermissions = userPermissionMapper.selectList(new LambdaQueryWrapper<UserPermission>().eq(UserPermission::getCommunityId,dto.getXqId()));

            return MyResponse.success(SyncDataBaseVO.builder().community(community).buildings(buildings).houses(houses).userPermissions(userPermissions).build());
        } catch (Exception e) {
            return MyResponse.fail(e.getMessage());
        }
    }

    /**
     * @Desc: 返回小区下业主id集合
     */
    @GetMapping("/people/{xqId}/{pwd}")
    public MyResponse people(@PathVariable String xqId, @PathVariable String pwd) {
        if (!SYNC_PWD.equals(pwd)) {
            return MyResponse.fail("错啦错啦");
        }
        List<OwnerHouse> ownerHouses = ownerHouseMapper.selectList(new LambdaQueryWrapper<OwnerHouse>().eq(OwnerHouse::getCommunityId, xqId));
        if (CollectionUtils.isEmpty(ownerHouses)) {
            return MyResponse.success();
        }
        return MyResponse.success(ownerHouses.stream().distinct().map(OwnerHouse::getOpenId).collect(Collectors.toList()));
    }

    /**
     * @Desc: 返回所有好友ID
     */
    @GetMapping("/friend/{xqId}/{pwd}")
    public MyResponse friend(@PathVariable String xqId, @PathVariable String pwd) {
        if (!SYNC_PWD.equals(pwd)) {
            return MyResponse.fail("错啦错啦");
        }
        List<OwnerFriend> ownerFriends = ownerFriendMapper.selectList(new LambdaQueryWrapper<OwnerFriend>().eq(OwnerFriend::getCommunityId, xqId));
        if (CollectionUtils.isEmpty(ownerFriends)) {
            return MyResponse.success();
        }
        return MyResponse.success(ownerFriends.stream().map(OwnerFriend::getId).collect(Collectors.toList()));
    }


    @PostMapping("/people")
    public MyResponse people(@RequestBody SyncDataPeopleDto dto) {
        if (ObjectUtils.isEmpty(dto) || StringUtils.isAnyBlank(dto.getXqId(), dto.getPwd()) || CollectionUtils.isEmpty(dto.getOpenIdList())) {
            return MyResponse.fail("入参不能为空");
        }
        if (!SYNC_PWD.equals(dto.getPwd())) {
            return MyResponse.fail("错啦错啦");
        }
        List<SyncDataPeopleVo> list = new ArrayList<>();
        for (String oid : dto.getOpenIdList()) {
            try {
                PublicUser publicUser = publicUserMapper.selectOne(new LambdaQueryWrapper<PublicUser>().eq(PublicUser::getOpenId, oid));
                Picture picture = pictureMapper.selectById(publicUser.getPictureId());
                publicUser.setPictureId(ImgUtil.imgToBase64(new URL(ossIntelnal(picture.getUrl()))));
                List<OwnerHouse> ownerHouseList = ownerHouseMapper.selectList(new LambdaQueryWrapper<OwnerHouse>().eq(OwnerHouse::getOpenId, oid));
                if (CollectionUtils.isEmpty(ownerHouseList)) {
                    throw new BizException("获取不到业主房屋列表");
                }
                list.add(SyncDataPeopleVo.builder()
                        .publicUser(publicUser)
                        .ownerHouseList(ownerHouseList)
                        .build());
            } catch (Exception e) {
                log.error("构造人员数据异常：人员openId:{},原因:{}", oid, e.getMessage());
            }
        }
        return MyResponse.success(list);
    }


    @PostMapping("/friend")
    public MyResponse friend(@RequestBody SyncDataFriendDto dto) {
        if (ObjectUtils.isEmpty(dto) || StringUtils.isAnyBlank(dto.getXqId(), dto.getPwd()) || CollectionUtils.isEmpty(dto.getIdList())) {
            return MyResponse.fail("入参不能为空");
        }
        if (!SYNC_PWD.equals(dto.getPwd())) {
            return MyResponse.fail("错啦错啦");
        }

        List<SyncDataFriendVo> list = new ArrayList<>();
        for (String oid : dto.getIdList()) {
            try {
                OwnerFriend ownerFriend = ownerFriendMapper.selectById(oid);
                Picture picture = pictureMapper.selectById(ownerFriend.getPictureId());
                ownerFriend.setPictureId(ImgUtil.imgToBase64(new URL(ossIntelnal(picture.getUrl()))));
                List<FriendHouse> friendHouseList = friendHouseMapper.selectList(new LambdaQueryWrapper<FriendHouse>().eq(FriendHouse::getFriendId, oid));
                if (CollectionUtils.isEmpty(friendHouseList)) {
                    throw new BizException("获取不到好友房屋列表");
                }
                list.add(SyncDataFriendVo.builder()
                        .ownerFriend(ownerFriend)
                        .friendHouseList(friendHouseList)
                        .build());
            } catch (Exception e) {
                log.error("构造好友数据异常：好友ID:{},原因：{}", oid, e.getMessage());
            }
        }
        return MyResponse.success(list);
    }


    private String ossIntelnal(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        return url.replaceAll("hangzhou", "hangzhou-internal");
    }


}
